﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using starLiGHT.GUI.Widgets;

namespace starLiGHT.GUI
{
    public class RadioButtonController
    {
        List<ICheckable> checkables = new List<ICheckable>();
        ICheckable currentSelection = null;

        public ICheckable CurrentSelection { get { return currentSelection; } }

        public bool AllowNoCheckedControl { get; set; }

        public event Action<ICheckable> SelectionChanged;


        public RadioButtonController(params ICheckable[] radiobuttons)
        {
            int firstCheckedIndex = -1;

            for (int i = 0; i < radiobuttons.Length; i++)
            {
                Add(radiobuttons[i]);

                if (firstCheckedIndex < 0 && radiobuttons[i].Checked)
                {
                    firstCheckedIndex = i;
                }
            }

            if(firstCheckedIndex >= 0)
            {
                CheckChanged(radiobuttons[firstCheckedIndex], null);
            }
        }

        public void Add(ICheckable radioButton)
        {
            checkables.Add(radioButton);
            radioButton.CheckChanged += CheckChanged;
        }

        void CheckChanged(object sender, EventArgs e)
        {
            ICheckable selection = (sender as ICheckable);
            if (currentSelection == selection)
            {
                if (AllowNoCheckedControl)
                {
                    currentSelection = null;
                    OnSelectionChanged(null);
                }
                else
                {
                    currentSelection.Checked = true;
                }
            }
            else if (selection != null && selection.Checked)
            {
                ICheckable prevSelection = currentSelection;
                currentSelection = selection;

                if (prevSelection != null)
                {
                    prevSelection.Checked = false;
                }
                OnSelectionChanged(currentSelection);
            }
        }

        private void OnSelectionChanged(ICheckable selection)
        {
            if (SelectionChanged != null)
            {
                SelectionChanged(selection);
            }
        }
    }
}
